package pay.serviceImpl;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import pay.portal.web.message.JPushPlusReq;
import pay.service.IMessageService;

import java.util.UUID;

/**
 * Created by Sheldon Chen on 2017/3/16.
 */
@Service
public class MessageServiceImpl implements IMessageService {
    private Logger logger = LoggerFactory
            .getLogger(MessageServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;

    @Value("${msg.server.name}")
    private String msgServerAddress;

    @Value("${msg.server.env}")
    private String env;

    @Override
    public String sendMsg(String aliases, String msg, String title, String menu, String msgTypeConstants) {
        UUID uuid = UUID.randomUUID();
        String uuidString = uuid.toString();
        String url = String.format("%s/jpushPlus/sendMsg/huacaitong", this.msgServerAddress);

        JPushPlusReq jPushPlusReq = new JPushPlusReq();
        jPushPlusReq.setAliases(aliases);
        jPushPlusReq.setMsg(msg);
        jPushPlusReq.setMenu(menu);
        jPushPlusReq.setTitle(title);
        jPushPlusReq.setUuid(uuidString);
        jPushPlusReq.setEnv(this.env);
        jPushPlusReq.setMsgTypeConstants(msgTypeConstants);
        jPushPlusReq.setChannel(1);

        JSONObject jsonObject = new JSONObject(jPushPlusReq);
        String requestJson = jsonObject.toString();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);

        try {
            Object resultString = this.restTemplate.postForEntity(url, entity, Object.class);
        } catch (Exception e) {
            logger.error("msg server error.", e);
        }

        String resultCode = "0";
//        if (resultString != null) {
//            JSONObject result = new JSONObject(resultString);
//            resultCode = result.getString("result");
//        }

        return resultCode;
    }

}
